package com.loveprogrammer.factory;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.loveprogrammer.factory.template.JobTemplate;
import com.loveprogrammer.model.Hero;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName JobFactory
 * @Description 英雄职业工厂
 * @Author admin
 * @Date 2024/2/7 15:49
 * @Version 1.0
 */
public class JobFactory {

    private static List<JobTemplate> templates;

    private static Map<Integer,JobTemplate> jobMap;

    static {
        try {
            // 读取配置文件，然后加载到weaponTemplates中
            ClassLoader classLoader = JobFactory.class.getClassLoader();
            InputStream inputStream = classLoader.getResourceAsStream("template/job.json");

            assert inputStream != null;
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            StringBuilder responseStrBuilder = new StringBuilder();

            String inputStr;
            while ((inputStr = streamReader.readLine()) != null)
                responseStrBuilder.append(inputStr);

            templates = JSONArray.parseArray(responseStrBuilder.toString(),JobTemplate.class);

            jobMap = templates.stream().collect(Collectors.toMap(JobTemplate::getId, e ->e));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<JobTemplate> getTemplates(){
        return templates;
    }

    public static Map<Integer, JobTemplate> getJobMap() {
        return jobMap;
    }

    public static Hero createHero(JobTemplate template, String name) throws IOException, ClassNotFoundException {
        Hero hero = new Hero(name, template);
        return hero;
    }

    public static void main(String[] args) {
        System.out.println("加载的职业有：" + JSON.toJSONString(templates));
    }

}
